<template>
  <!-- 导航栏 -->
  <van-nav-bar 
    title="我的收货地址" 
    left-text="返回" 
    left-arrow 
    @click-left="back" 
  />

  <!-- 收货地址列表 -->
  <van-address-list 
    v-if="action=='order'"
    v-model="AddressDefault" 
    :list="AddressList" 
    default-tag-text="默认" 
    @add="add" 
    @select="order"
    @edit="edit" 
  />

  <van-address-list 
    v-else
    v-model="AddressDefault" 
    :list="AddressList" 
    default-tag-text="默认" 
    @add="add" 
    @select="select"
    @edit="edit" 
  />
</template>


<script>
  export default {
    name: 'AddressIndex',
    created() {

      this.action=this.$route.query.action ? this.$route.query.action :'';
      //获取收货地址
      this.AddressData()
    },
    data() {
      return {
        action:'',
        LoginUser: this.$cookies.get('LoginUser'),
        AddressList: [], //地址列表
        AddressDefault: 0, //默认选中地址的ID
      }
    },
    methods: {
      //  返回上一层
      back() {
        this.$router.go(-1)
      },
      
      //获取收货地址列表
      async AddressData() {
        //调用接口
        var result = await this.$api.AddressIndex({ userid: this.LoginUser.id }
        )

        var data = result.data
        var list = []

        if (data.length <= 0) {
          this.$notify({
            title: '提示信息',
            message: '暂无收货地址'
          })

          return false
        }

        //找出默认的收货地址
        for (var item of data) {
          //默认收货地址
          if (item.status == 1) {
            this.AddressDefault = item.id
          }

          //组装数据结构
          var address = {
            id: item.id,
            name: item.consignee,
            tel: item.mobile,
            address: `${item.region_text} ${item.address}`,
            isDefault: item.status == 1 ? true : false
          }

          list.push(address)
        }

        //覆盖data数据
        this.AddressList = list

      },
     
      // 添加
      add() {
        //跳转
        this.$router.push('/user/address/add')
      },
      
      //切换默认地址
      async select(item) {
        var addrid = item.id ? item.id : 0

        var data = {
          userid: this.LoginUser.id,
          addrid: addrid
        }

        //调用接口
        var result = await this.$api.AddressCheck(data)

        //重新调用过一遍请求列表的方法
        this.AddressData()
      },

      // 编辑地址
      edit(address) {                                                
        var addrid=address.id
        // console.log(addrid);

        // 跳转需要传参
        this.$router.push({path:'/user/address/edit', query:{addrid: addrid}})
      },

      async order(item){
        //组装数据
        var data = {
          id: item.id,
          consignee: item.name,
          mobile: item.tel,
          region_text: item.address
        }

        //存放到cookie中
        this.$cookies.set('address', data)

        //回退
        this.$router.go(-1)
      }
    }
  }
</script>